package com.yejiarong.gateway.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.web.server.SecurityWebFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

/**
 * @author YeJR
 */
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    private final AuthConfig authConfig;

    public SecurityConfig(AuthConfig authConfig) {
        this.authConfig = authConfig;
    }


    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        http
                .authorizeExchange(exchanges -> exchanges
                        .pathMatchers(authConfig.getPermit().getEndpoints()).permitAll()
                        .anyExchange().authenticated()
                )
                .oauth2Login(withDefaults())  // 启用 OAuth2 登录
                .oauth2Client(withDefaults()) // 启用 OAuth2 客户端
                .csrf(ServerHttpSecurity.CsrfSpec::disable); // 通常 API 网关需要禁用 CSRF

        return http.build();
    }
}
